/**
 * 分数计算器
 */

class ScoreCalculator {
	/**
	 * 计算速判练习分数
	 * @param {Array} correctPairs 正确配对
	 * @param {Array} userAnswers 用户答案
	 * @returns {Object} 分数结果
	 */
	static calculateSpeedJudgeScore(correctPairs, userAnswers) {
		const totalQuestions = correctPairs.length;
		let correctCount = 0;
		
		// 检查每个用户答案是否正确
		userAnswers.forEach(userAnswer => {
			const correctPair = correctPairs.find(pair => 
				pair.fractionId === userAnswer.fractionId
			);
			
			if (correctPair && correctPair.decimalId === userAnswer.decimalId) {
				correctCount++;
			}
		});
		
		const accuracy = totalQuestions > 0 ? (correctCount / totalQuestions) * 100 : 0;
		const score = Math.round(accuracy);
		
		return {
			totalQuestions,
			correctCount,
			wrongCount: totalQuestions - correctCount,
			accuracy: Math.round(accuracy * 100) / 100, // 保留2位小数
			score,
			isPerfect: correctCount === totalQuestions
		};
	}
	
	/**
	 * 计算速算练习分数
	 * @param {Array} questions 题目数组
	 * @param {number} totalTime 总用时（秒）
	 * @returns {Object} 分数结果
	 */
	static calculateSpeedCalcScore(questions, totalTime) {
		const totalQuestions = questions.length;
		const correctCount = questions.filter(q => q.isCorrect).length;
		const wrongCount = totalQuestions - correctCount;
		const accuracy = totalQuestions > 0 ? (correctCount / totalQuestions) * 100 : 0;
		
		// 分数计算公式：题目数 × 正确率 ÷ 答题时间
		// 为了得到合理的分数，使用以下公式：
		// 基础分 = 题目数 × 正确率
		// 时间奖励 = 基础分 × (60 / 答题时间) * 0.5 （60秒内完成有时间奖励）
		// 最终分数 = 基础分 + 时间奖励（如果答题时间 <= 60秒）
		
		const baseScore = totalQuestions * (accuracy / 100);
		let timeBonus = 0;
		
		if (totalTime > 0 && totalTime <= 60) {
			timeBonus = baseScore * (60 / totalTime) * 0.5;
		}
		
		const finalScore = Math.round((baseScore + timeBonus) * 10) / 10; // 保留1位小数
		
		// 计算平均用时
		const averageTime = totalTime / totalQuestions;
		
		// 分析错误类型
		const errorAnalysis = this.analyzeErrors(questions);
		
		return {
			totalQuestions,
			correctCount,
			wrongCount,
			accuracy: Math.round(accuracy * 100) / 100,
			totalTime,
			averageTime: Math.round(averageTime * 100) / 100,
			baseScore: Math.round(baseScore * 100) / 100,
			timeBonus: Math.round(timeBonus * 100) / 100,
			score: finalScore,
			isPerfect: correctCount === totalQuestions,
			errorAnalysis
		};
	}
	
	/**
	 * 分析答题错误
	 * @param {Array} questions 题目数组
	 * @returns {Object} 错误分析
	 */
	static analyzeErrors(questions) {
		const errorsByOperation = {
			add: 0,
			subtract: 0,
			multiply: 0,
			divide: 0
		};
		
		const errorsByValueType = {
			integer: 0,
			decimal: 0,
			percentage: 0
		};
		
		const wrongQuestions = questions.filter(q => !q.isCorrect);
		
		wrongQuestions.forEach(question => {
			if (errorsByOperation.hasOwnProperty(question.operation)) {
				errorsByOperation[question.operation]++;
			}
			
			if (errorsByValueType.hasOwnProperty(question.valueType)) {
				errorsByValueType[question.valueType]++;
			}
		});
		
		return {
			totalErrors: wrongQuestions.length,
			errorsByOperation,
			errorsByValueType,
			mostDifficultOperation: this.findMostDifficult(errorsByOperation),
			mostDifficultValueType: this.findMostDifficult(errorsByValueType)
		};
	}
	
	/**
	 * 找出最困难的类型
	 * @param {Object} errorMap 错误映射
	 * @returns {string} 最困难的类型
	 */
	static findMostDifficult(errorMap) {
		let maxErrors = 0;
		let mostDifficult = null;
		
		for (const [type, count] of Object.entries(errorMap)) {
			if (count > maxErrors) {
				maxErrors = count;
				mostDifficult = type;
			}
		}
		
		return mostDifficult;
	}
	
	/**
	 * 计算练习级别
	 * @param {number} score 分数
	 * @param {number} accuracy 正确率
	 * @returns {Object} 级别信息
	 */
	static calculateLevel(score, accuracy) {
		let level = 'beginner';
		let levelName = '初学者';
		let nextLevelScore = 50;
		
		if (score >= 200 && accuracy >= 95) {
			level = 'master';
			levelName = '大师';
			nextLevelScore = null;
		} else if (score >= 150 && accuracy >= 90) {
			level = 'expert';
			levelName = '专家';
			nextLevelScore = 200;
		} else if (score >= 100 && accuracy >= 85) {
			level = 'advanced';
			levelName = '高级';
			nextLevelScore = 150;
		} else if (score >= 50 && accuracy >= 75) {
			level = 'intermediate';
			levelName = '中级';
			nextLevelScore = 100;
		}
		
		return {
			level,
			levelName,
			nextLevelScore,
			progress: nextLevelScore ? Math.min(100, (score / nextLevelScore) * 100) : 100
		};
	}
	
	/**
	 * 计算速判选择题分数
	 * @param {Array} questions 题目数组
	 * @param {number} totalTime 总用时（秒）
	 * @returns {Object} 分数结果
	 */
	static calculateSpeedJudgeChoiceScore(questions, totalTime) {
		const totalQuestions = questions.length;
		const correctCount = questions.filter(q => q.isCorrect).length;
		const wrongCount = totalQuestions - correctCount;
		const accuracy = totalQuestions > 0 ? (correctCount / totalQuestions) * 100 : 0;
		
		// 选择题分数计算：基础分 + 时间奖励
		// 基础分 = 正确题数 × 10
		// 时间奖励 = 基础分 × (30 / 答题时间) * 0.3 （30秒内完成有时间奖励）
		// 最终分数 = 基础分 + 时间奖励（如果答题时间 <= 30秒）
		
		const baseScore = correctCount * 10;
		let timeBonus = 0;
		
		if (totalTime > 0 && totalTime <= 30) {
			timeBonus = baseScore * (30 / totalTime) * 0.3;
		}
		
		const finalScore = Math.round((baseScore + timeBonus) * 10) / 10;
		
		// 计算平均用时
		const averageTime = totalTime / totalQuestions;
		
		return {
			totalQuestions,
			correctCount,
			wrongCount,
			accuracy: Math.round(accuracy * 100) / 100,
			totalTime,
			averageTime: Math.round(averageTime * 100) / 100,
			baseScore: Math.round(baseScore * 100) / 100,
			timeBonus: Math.round(timeBonus * 100) / 100,
			score: finalScore,
			isPerfect: correctCount === totalQuestions
		};
	}
	
	/**
	 * 计算速算选择题分数
	 * @param {Array} questions 题目数组
	 * @param {number} totalTime 总用时（秒）
	 * @returns {Object} 分数结果
	 */
	static calculateSpeedCalcChoiceScore(questions, totalTime) {
		const totalQuestions = questions.length;
		const correctCount = questions.filter(q => q.isCorrect).length;
		const wrongCount = totalQuestions - correctCount;
		const accuracy = totalQuestions > 0 ? (correctCount / totalQuestions) * 100 : 0;
		
		// 选择题分数计算：基础分 + 时间奖励
		// 基础分 = 正确题数 × 10
		// 时间奖励 = 基础分 × (45 / 答题时间) * 0.4 （45秒内完成有时间奖励）
		// 最终分数 = 基础分 + 时间奖励（如果答题时间 <= 45秒）
		
		const baseScore = correctCount * 10;
		let timeBonus = 0;
		
		if (totalTime > 0 && totalTime <= 45) {
			timeBonus = baseScore * (45 / totalTime) * 0.4;
		}
		
		const finalScore = Math.round((baseScore + timeBonus) * 10) / 10;
		
		// 计算平均用时
		const averageTime = totalTime / totalQuestions;
		
		// 分析错误类型
		const errorAnalysis = this.analyzeErrors(questions);
		
		return {
			totalQuestions,
			correctCount,
			wrongCount,
			accuracy: Math.round(accuracy * 100) / 100,
			totalTime,
			averageTime: Math.round(averageTime * 100) / 100,
			baseScore: Math.round(baseScore * 100) / 100,
			timeBonus: Math.round(timeBonus * 100) / 100,
			score: finalScore,
			isPerfect: correctCount === totalQuestions,
			errorAnalysis
		};
	}
	
	/**
	 * 计算公式选择题分数
	 * @param {Array} questions 题目数组
	 * @param {number} totalTime 总用时（秒）
	 * @returns {Object} 分数结果
	 */
	static calculateSpeedFormulaChoiceScore(questions, totalTime) {
		const totalQuestions = questions.length;
		const correctCount = questions.filter(q => q.isCorrect).length;
		const wrongCount = totalQuestions - correctCount;
		const accuracy = totalQuestions > 0 ? (correctCount / totalQuestions) * 100 : 0;
		
		// 选择题分数计算：基础分 + 时间奖励
		// 基础分 = 正确题数 × 10
		// 时间奖励 = 基础分 × (45 / 答题时间) * 0.4 （45秒内完成有时间奖励）
		// 最终分数 = 基础分 + 时间奖励（如果答题时间 <= 45秒）
		
		const baseScore = correctCount * 10;
		let timeBonus = 0;
		
		if (totalTime > 0 && totalTime <= 45) {
			timeBonus = baseScore * (45 / totalTime) * 0.4;
		}
		
		const finalScore = Math.round((baseScore + timeBonus) * 10) / 10;
		
		// 计算平均用时
		const averageTime = totalTime / totalQuestions;
		
		return {
			totalQuestions,
			correctCount,
			wrongCount,
			accuracy: Math.round(accuracy * 100) / 100,
			totalTime,
			averageTime: Math.round(averageTime * 100) / 100,
			baseScore: Math.round(baseScore * 100) / 100,
			timeBonus: Math.round(timeBonus * 100) / 100,
			score: finalScore,
			isPerfect: correctCount === totalQuestions
		};
	}
	
	/**
	 * 通用分数计算函数（兼容现有代码）
	 * @param {Object} params 参数对象
	 * @param {number} params.correctCount 正确题数
	 * @param {number} params.totalCount 总题数
	 * @param {number} params.totalTime 总用时
	 * @param {string} params.questionType 题目类型
	 * @returns {number} 分数
	 */
	static calculateScore({ correctCount, totalCount, totalTime, questionType }) {
		const accuracy = totalCount > 0 ? (correctCount / totalCount) * 100 : 0;
		
		if (questionType === 'choice') {
			// 选择题基础分数计算
			const baseScore = correctCount * 10;
			let timeBonus = 0;
			
			// 根据题目数量调整时间奖励阈值
			const timeThreshold = totalCount <= 10 ? 30 : 45;
			const bonusMultiplier = totalCount <= 10 ? 0.3 : 0.4;
			
			if (totalTime > 0 && totalTime <= timeThreshold) {
				timeBonus = baseScore * (timeThreshold / totalTime) * bonusMultiplier;
			}
			
			return Math.round((baseScore + timeBonus) * 10) / 10;
		}
		
		// 默认计算方式
		return Math.round(accuracy);
	}
	
	/**
	 * 生成练习建议
	 * @param {Object} scoreResult 分数结果
	 * @returns {Array} 建议列表
	 */
	static generateSuggestions(scoreResult) {
		const suggestions = [];
		
		if (scoreResult.accuracy < 60) {
			suggestions.push('建议多练习基础运算，提高计算准确率');
		} else if (scoreResult.accuracy < 80) {
			suggestions.push('计算准确率还有提升空间，可以放慢速度确保正确性');
		}
		
		if (scoreResult.averageTime > 10) {
			suggestions.push('可以通过更多练习来提高计算速度');
		} else if (scoreResult.averageTime < 3) {
			suggestions.push('计算速度很快，注意保持准确率');
		}
		
		if (scoreResult.errorAnalysis && scoreResult.errorAnalysis.mostDifficultOperation) {
			const operationNames = {
				add: '加法',
				subtract: '减法',
				multiply: '乘法',
				divide: '除法'
			};
			const opName = operationNames[scoreResult.errorAnalysis.mostDifficultOperation] || '某种运算';
			suggestions.push(`${opName}运算出错较多，建议重点练习`);
		}
		
		if (scoreResult.isPerfect) {
			suggestions.push('完美答题！可以尝试更高难度的练习');
		}
		
		return suggestions;
	}
}

export default ScoreCalculator;